"""
数据模型
"""

import json
from datetime import datetime
from decimal import Decimal

from pydantic import BaseModel, field_validator, Field

from common.base_enums import MeterPhase, MeterType


class RawTelemetry(BaseModel):
	meter_code: str
	ts: datetime
	voltage: Decimal
	current: Decimal
	watt: Decimal
	total_kwh: Decimal
	temperature1: Decimal
	temperature2: Decimal

	@field_validator('voltage', 'current', 'watt', 'total_kwh',
					 'temperature1', 'temperature2', mode='before')
	@classmethod
	def _to_decimal(cls, v):
		if v is None:
			raise ValueError('field missing')
		return Decimal(str(v))

	@staticmethod
	def from_payload(meter_code: str, payload: dict) -> "RawTelemetry":
		"""从硬件 payload 构造"""
		return RawTelemetry(
			meter_code=meter_code,
			ts=datetime.fromtimestamp(int(payload["ts"])),
			voltage=payload["V"],
			current=payload["C"],
			watt=payload["kW"],
			total_kwh=payload["kWh"],
			temperature1=payload.get("T1", 0),
			temperature2=payload.get("T2", 0),
		)


class TelemetryRow(BaseModel):
	"""单相或三相其中一行的内部表示"""
	msg_id: str
	meter_code: str
	phase: MeterPhase
	meter_type: MeterType
	ts: datetime
	voltage: Decimal
	current: Decimal
	watt: Decimal
	total_kwh: Decimal
	temperature1: Decimal
	temperature2: Decimal
	ext_json: dict = Field(default_factory=dict)
	raw_snapshot: dict = Field(default_factory=dict)
	quality: str = "GOOD"

	def to_db_tuple(self):
		"""返回与表列顺序一致的元组，供批量插入"""
		return (
			self.msg_id,
			self.meter_code,
			self.phase.value,
			self.ts,
			self.voltage,
			self.current,
			self.watt,
			self.total_kwh,
			self.temperature1,
			self.temperature2,
			self.quality,  # 硬化列
			json.dumps(self.ext_json, ensure_ascii=False),
		)
